﻿using System;
using System.Collections.Generic;
using System.Text;
using xl.demo.models;
using xycn.common;
using xycn.IDbService;
using xycn.pluginsupport.BaseHelperPlugins;
using xycn.pluginsupport.ControllerPlugins;

namespace xl.demo.webapi
{

    /// <summary>
    /// 会员管理
    /// </summary>
    public class MembersController : BaseController
    {
        /// <summary>
        /// 基类数据查询类
        /// </summary>
        //public DbHelper<Members> _dbhelper = new DbHelper<Members>();
        IDbService _dbhelper = DbHelper.CreateDbService("SqlSugarInterface");

        /// <summary>
        /// 登录认证
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/Login")]
        [AllowAnonymous]
        public ReponseContext Login()
        {
            try
            {
                var token = AuthHelper.CreateSign(new xycn.IAuthorize.SignInfo()
                {
                    id = "123123",
                    name = "desdf",
                    groupid = "123123123",
                    extend1 = "ex1"
                });

                return _success("签发Token:  Bearer {Token} " + token);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/Login");
            }
        }


        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/HelloWord")]
        [DataCache(CacheMinutes = 100)]
        public ReponseContext HelloWord([FromQuery] string token)
        {
            try
            {
                var auth = base.GetAuthInfo();

                return _success("这是一个测试消息" + DateTime.Now.ToString() + auth.ToJsonString());
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetList");
            }
        }

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/test2")]
        public ReponseContext test2([FromQuery] string token)
        {
            try
            {
                var auth = base.GetAuthInfo();

                return _success("这是一个测试消息" + DateTime.Now.ToString() + auth.ToJsonString() + "---" + token);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetList");
            }
        }

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/GetAllList")]
        public ReponseContext GetAllList()
        {
            try
            {
                var res = _dbhelper.GetList<Members>(null);

                if (res.IsSucceed)
                {
                    return _success(res.Data);
                }
                return _fail(res.Message);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetList");
            }
        }

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/GetList")]
        public ReponseContext GetListAsync([FromBody] RequestContext model)
        {
            try
            {
                var req = model.Data.ToDictionaryWithKeyToLower();

                var res = _dbhelper.GetListByDic<Members>(req);

                return _success(res);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetList");
            }
        }

        /// <summary>
        /// 分页查询数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/GetListPage")]
        public ReponseContext GetListPage([FromBody] RequestContext model)
        {
            try
            {
                int totalNum = 0;

                var res = _dbhelper.GetListByPage<Members>(p => p.KID == 1, model.Page, model.Limit, ref totalNum);

                if (res.IsSucceed)
                {
                    return _success(res.Data, 0, "", totalNum);
                }
                return _fail(res.Message);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetListPage");
            }
        }

        /// <summary>
        /// 分页查询数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/GetCount")]
        public ReponseContext GetCount()
        {
            try
            {
                var res = _dbhelper.GetCount<Members>();

                if (res.IsSucceed)
                {
                    return _success(res.Data);
                }
                return _fail(res.Message);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetOne");
            }
        }

        /// <summary>
        /// 分页查询数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/GetOne")]
        public ReponseContext GetOne()
        {
            try
            {
                var res = _dbhelper.GetOne<Members>(p => p.KID == 1);

                if (res.IsSucceed)
                {
                    return _success(res.Data);
                }
                return _fail(res.Message);
            }
            catch (Exception ex)
            {
                return _error(ex, "/Members/GetOne");
            }
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/UpdateItem")]
        public ReponseContext UpdateItem([FromBody] RequestContext model)
        {
            try
            {
                //暂未实现
                return _success(model);
            }
            catch (Exception ex)
            {
                return _error(ex, "Members/GetListByPage请求异常");
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/AddItem")]
        public ReponseContext AddItem([FromBody] RequestContext model)
        {
            var entity = model.Data.GetModelByJson<Members>();
            entity.CreateTime = DateTime.Now;

            var res = _dbhelper.AddItem(entity);

            return _success(res);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/DeleteItem")]
        public ReponseContext DeleteItem([FromBody] RequestContext model)
        {
            var res = _dbhelper.DeleteItem<Members>(p => p.KID == 2);

            return _success(res);
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/UpdateFields")]
        public ReponseContext UpdateFields([FromBody] RequestContext model)
        {
            var res = _dbhelper.UpdateFields<Members>(p => new Members()
            {
                WxNickName = "修改sss",
                CreateTime = DateTime.Now
            }, p => p.KID == 1);

            return _success(res);
        }


        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpMethod(HttpMethodType.POST, "/Members/UpdateOneField")]
        public ReponseContext UpdateOneField([FromBody] RequestContext model)
        {
            var res = _dbhelper.UpdateOneField<Members>(p => p.WxNickName == "sdssdfsdfsdf", p => p.KID == 2);
            return _success(res);
        }


        [HttpMethod(HttpMethodType.POST, "/Members/TestApi")]
        public ReponseContext TestApi([FromQuery] string api, [FromBody] RequestContext model)
        {
            switch (api.ToLower())
            {
                case "getdatatable":
                    {
                        var res = _dbhelper.GetDataTable(model.Data.ToString());
                        return _success(res.ToDictionary());
                    }
                case "getdatasetall":
                    {
                        var res = _dbhelper.GetDataSetAll(model.Data.ToString());
                        return _success(res.ToJsonString());
                    }
                case "getscalar":
                    {
                        var res = _dbhelper.GetScalar(model.Data.ToString());
                        return _success(res.ToJsonString());
                    }
                case "getstring":
                    {
                        var res = _dbhelper.GetString(model.Data.ToString());
                        return _success(res.ToJsonString());
                    }
                case "executecommand":
                    {
                        var res = _dbhelper.ExecuteCommand(model.Data.ToString());
                        return _success(res.ToJsonString());
                    }
                case "sqlquery":
                    {
                        var res = _dbhelper.SqlQuery<Members>(model.Data.ToString(), new { id = 123, kkk = 123123, dsd = "1231234" });
                        return _success(res.ToJsonString());
                    }
                case "tran_aud":
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine("tran_aud事务开始");
                        _dbhelper.BeginTran();


                        var addret = _dbhelper.AddItem(new Members()
                        {
                            WxNickName = DateTime.Now.ToString(),
                            CreateTime = DateTime.Now
                        });
                        sb.AppendLine("添加数据：" + addret.ToJsonString());

                        var newname = "修改wxnickname" + DateTime.Now.ToString();
                        var kid = Convert.ToInt32(addret.Data);

                        var upret = _dbhelper.UpdateOneField<Members2>(p => p.WxNickName2 == newname
                        , p => p.KID2 == kid);
                        sb.AppendLine("修改数据：" + upret.ToJsonString());

                        if (!upret.IsSucceed)
                        {
                            sb.AppendLine("失败");
                            _dbhelper.RollbackTran();
                        }
                        else
                        {
                            _dbhelper.CommitTran();
                        }
                        //var delret = _dbhelper.DeleteItem(p => p.KID == Convert.ToInt32(addret.Data));
                        //sb.AppendLine("删除数据：" + delret.ToJsonString());

                        sb.AppendLine("提交事务");

                        return _success(addret, 500, sb.ToString());
                    }

                case "tran_error":
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine("tran_error事务开始");
                        _dbhelper.BeginTran();


                        var addret = _dbhelper.AddItem(new Members()
                        {
                            WxNickName = DateTime.Now.ToString(),
                            CreateTime = DateTime.Now
                        });
                        sb.AppendLine("添加数据：" + addret.ToJsonString());

                        var newname = "修改wxnickname" + DateTime.Now.ToString();
                        var kid = Convert.ToInt32(addret.Data);
                        var upret = _dbhelper.UpdateOneField<Members>(p => p.WxNickName == newname
                        , p => p.KID == kid);

                        sb.AppendLine("修改数据：" + upret.ToJsonString());

                        _dbhelper.RollbackTran();
                        sb.AppendLine("提交事务");

                        return _success(addret, 0, sb.ToString());
                    }
                case "groupby":
                    {
                        var res = _dbhelper.GroupBy<Members>(p => p.KID > 4, k => k.GroupId);
                        return _success(res);
                    }
                case "relation":
                    {
                        int rowcount = 0;
                        var res = _dbhelper.GetList<Members, Members2, MemberView>((a, b) => true, "a.kid=b.kid", JoinType.Left, a => a.WxNickName.Contains("张三"), a => a.KID, OrderType.Desc, ref rowcount, "a.*,b.kid as bbbkid");

                        //var res = _dbhelper.GetList<Members, Members2, MemberView>((a, b) => true, "a.kid=b.kid", JoinType.Left, a => a.WxNickName.Contains("张三"), a => a.KID, OrderType.Desc, (a) => new
                        //{
                        //    KID = b.KID2,
                        //    WxNickName = b.WxNickName,
                        //    bName=b.WxNickName2
                        //});

                        return _success(res);
                    }

                case "relationwhere2":
                    {
                        int rowcount = 0;
                        var res = _dbhelper.GetList<Members, Members2, MemberView>((a, b) => true, "a.kid=b.kid", JoinType.Left, (a, b) => b.KID2 == 1 && b.KID2 < 100, a => a.KID, OrderType.Desc, ref rowcount, "a.*,b.kid as bbbkid");

                        //var res = _dbhelper.GetList<Members, Members2, MemberView>((a, b) => true, "a.kid=b.kid", JoinType.Left, a => a.WxNickName.Contains("张三"), a => a.KID, OrderType.Desc, (a) => new
                        //{
                        //    KID = b.KID2,
                        //    WxNickName = b.WxNickName,
                        //    bName=b.WxNickName2
                        //});

                        return _success(res);
                    }
                case "leftjoin4":
                    {
                        List<string> joinwhere = new List<string>();
                        joinwhere.Add("a.kid=b.kid2");
                        joinwhere.Add("b.kid2=c.kid3");
                        joinwhere.Add("c.kid3=d.kid3");
                        joinwhere.Add("d.kid3=e.kid3");

                        List<JoinType> sqlJoinType = new List<JoinType>();
                        sqlJoinType.Add(JoinType.Left);
                        sqlJoinType.Add(JoinType.Left);
                        sqlJoinType.Add(JoinType.Left);
                        sqlJoinType.Add(JoinType.Left);
                        sqlJoinType.Add(JoinType.Left);

                        int rowCount = 0;

                        var res = _dbhelper.GetList<Members, Members2, Members3, Members4, Members5, MemberView>((a, b, c, d, e) => true, joinwhere, sqlJoinType, (a, b, c, d, e) => a.KID == 1 && b.KID2 == 1 && c.KID3 == 1 && d.KID3 == 1 && e.KID3 == 1 && e.WxNickName3.Contains(model.AppName), a => a.KID, OrderType.Desc, ref rowCount);

                        return _success(res, 0, "ok", rowCount);
                    }

                case "relation2":
                    {
                        //xycn.common.LogHelper.Info("tetsete");
                        //var res = _dbhelper.GetList<Members, Members2, MemberView>((a, b) => new JoinQueryInfos(
                        //            JoinType.Left, a.KID == b.KID
                        //       ), a => a.WxNickName == "we" && a.KID > 2, k => k.KID, OrderType.Asc);

                        List<string> joinwhere = new List<string>();
                        joinwhere.Add("a.kid=b.kid2 and a.GroupId=b.kid2 and b.kid2>20 and b.kid<25 ");
                        joinwhere.Add("b.kid2=c.kid3");

                        List<JoinType> sqlJoinType = new List<JoinType>();
                        sqlJoinType.Add(JoinType.Left);
                        sqlJoinType.Add(JoinType.Left);

                        int rowCount = 0;

                        var res = _dbhelper.GetList<Members, Members2, Members3, MemberView>((a, b, c) => true, joinwhere, sqlJoinType, a => a.KID == 1, a => a.KID, OrderType.Desc, ref rowCount);

                        return _success(res, 0, "ok", rowCount);
                    }
                case "adds":
                    {
                        xycn.common.LogHelper.Info("adds");
                        var mems = new List<Members>();

                        for (int i = 0; i < 80; i++)
                        {
                            mems.Add(new Members()
                            {
                                WxNickName = i.ToString() + "---" + DateTime.Now.ToString(),
                                GroupId = i,
                                CreateTime = DateTime.Now
                            });
                        }

                        var res = _dbhelper.AddItems<Members>(mems);

                        return _success(res);
                    }
                case "ignore":
                    {
                        xycn.common.LogHelper.Info("Ignore");

                        var mem = new Members()
                        {
                            WxNickName = "ign更新",
                            GroupId = 123123,
                            CreateTime = DateTime.Now
                        };

                        var res = _dbhelper.UpdateFieldsIgnore<Members>(p => new Members()
                        {
                            WxNickName = "ign更新",
                            GroupId = 123123,
                            CreateTime = DateTime.Now,
                            KID = 123,
                            k1 = "11",
                            k2 = "22",
                            k3 = "33",
                            k4 = "44",
                            k5 = "55",
                            k6 = "66",
                        }, p => p.KID == 1);

                        return _success(res);
                    }
                case "3yuan1":
                    {
                        int totalNum = 0;

                        var res = _dbhelper.GetListByPage<Members>(p => p.KID == (string.IsNullOrWhiteSpace(model.AppName) ? 10 : 20), 1, 10, ref totalNum);

                        return _success(res);
                    }
                case "3yuan2":
                    {
                        int totalNum = 0;

                        var res = _dbhelper.GetListByPage<Members>(p => string.IsNullOrWhiteSpace(model.AppName) ? p.KID < 50 : p.KID > 50, 1, 10, ref totalNum);

                        return _success(res);
                    }
                    //case "upentity":
                    //    {
                    //        LogHelper.Info("upentity");

                    //        var mem = new Members()
                    //        {
                    //            WxNickName = "ign更新",
                    //            GroupId = 123123,
                    //            CreateTime = DateTime.Now
                    //        };

                    //        var res = _dbhelper.UpdateByEntity<Members>(mem, p => p.KID == 1, p => new { p.CreateTime, p.GroupId });

                    //        return _success(res);
                    //    }
            }

            return _fail("无执行分支");
        }
    }


    /// <summary>
    /// 测试Class 待加载依赖性后使用dll
    /// </summary>
    /*public class Members
    {
        public int KID { get; set; }

        public string WxNickName { get; set; }


        public DateTime CreateTime { get; set; }
    }*/
}
